package com.gitee.melin.bee.util;

import com.gitee.melin.bee.core.spring.security.LoginUserDetails;
import java.util.Objects;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtils {

    private static ThreadLocal<Boolean> tenantThreadStatus = new ThreadLocal<>();

    public static void tenantDisabled() {
        tenantThreadStatus.set(false);
    }

    public static void tenantEnabled() {
        tenantThreadStatus.set(true);
    }

    public static Boolean tenantStatus() {
        Boolean status = tenantThreadStatus.get();

        return Objects.isNull(status) ? true : status;
    }

    public static boolean checkIfLogined() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth instanceof UsernamePasswordAuthenticationToken) {
            return true;
        }
        return false;
    }

    public static Long tenantId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth instanceof UsernamePasswordAuthenticationToken) {
            UsernamePasswordAuthenticationToken ga = (UsernamePasswordAuthenticationToken) auth;
            LoginUserDetails user = (LoginUserDetails) ga.getPrincipal();
            return user.getTenantId();
        }
        return null;
    }

    public static String currentUserName() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth instanceof UsernamePasswordAuthenticationToken) {
            UsernamePasswordAuthenticationToken ga = (UsernamePasswordAuthenticationToken) auth;
            return ga.getName();
        }
        return null;
    }

    public static String getFullUserName() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth instanceof UsernamePasswordAuthenticationToken) {
            UsernamePasswordAuthenticationToken ga = (UsernamePasswordAuthenticationToken) auth;
            LoginUserDetails user = (LoginUserDetails) ga.getPrincipal();
            return user.getCnName() + "#" + user.getUsername();
        }
        return null;
    }
}
